package com.itheima.mm.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mm.context.BaseContext;
import com.itheima.mm.dto.CatalogDTO;
import com.itheima.mm.entity.CatalogPageQueryParams;
import com.itheima.mm.entity.PageResult;
import com.itheima.mm.entity.QueryPageBean;
import com.itheima.mm.mapper.CatalogMapper;
import com.itheima.mm.pojo.Catalog;
import com.itheima.mm.service.CatalogService;
import com.itheima.mm.utils.DateUtils;
import com.itheima.mm.vo.CatalogVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Description CatalogServiceImpl
 * @Author yunchuan
 * @Date 2024-06-27
 */
@Service
public class CatalogServiceImpl implements CatalogService {

    @Autowired
    private CatalogMapper catalogMapper;

    //添加学科目录
    @Override
    public void add(CatalogDTO catalogDTO) {
        Catalog catalog = new Catalog();

        BeanUtils.copyProperties(catalogDTO, catalog);

        catalog.setCreateDate(DateUtils.parseDate2String(new Date()));//系统当前时间
        catalog.setStatus(0);//启用
        catalog.setUserId(BaseContext.getCurrentId());
        catalogMapper.add(catalog);
    }
    //学科目录分页查询
    @Override
    public PageResult findListByPage(QueryPageBean<CatalogPageQueryParams> queryPageBean) {
        //设置分页参数
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());

        //执行查询
        CatalogPageQueryParams queryParams=queryPageBean.getQueryParams();
        List<CatalogVO> catalogList =  catalogMapper.findByCondition(queryParams);
        Page<CatalogVO> page=(Page<CatalogVO>)catalogList;

        return new PageResult(page.getTotal(), page.getResult());

    }
    //学科目录删除
    @Override
    public void delete(Integer id) {
        try{
            catalogMapper.delete(id);
        }catch(Exception e){
            throw new RuntimeException("有关联的面试题无法删除");
        }
    }

    //学科目录修改
    @Override
    public void update(CatalogDTO catalogDTO) {
        Catalog catalog = new Catalog();
        BeanUtils.copyProperties(catalogDTO, catalog);
        catalog.setUserId(BaseContext.getCurrentId());
        catalogMapper.update(catalog);
    }
    //学科目录禁用
    public boolean disableCatalog(Integer id) {
        // 假设 status = 1 表示禁用，0 表示启用
        int result = catalogMapper.updateCatalogStatus(id, 1);
        return result > 0;
    }

    //学科目录启用
    public boolean enableCatalog(Integer id) {
        // 假设 status = 0 表示启用，1 表示禁用
        int result = catalogMapper.updateCatalogStatus(id, 0);
        return result > 0;
    }
}
